package com.cg.service;

import com.alibaba.fastjson.JSON;
import com.cg.common.KeyCommon;
import com.cg.utils.TokenUtils;
import com.cg.dto.LoginPatientUserDto;
import com.cg.vo.LoginPatientUserVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName PatientUserTokenServiceImpl
 * @Description TODO
 * @Author CG
 * @Date 2024/1/5 19:39
 **/
public class PatientUserTokenServiceImpl implements PatientUserTokenService{


    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Value("${patientUserTokenTimeOut}")
    private Long patientUserTokenTimeOut;

    /**
     * 保存用户信息到redis中
     */
    @Override
    public void setPatientUserToken(LoginPatientUserDto loginPatientUserDto) {
        //生成token
        String token = TokenUtils.createToken(loginPatientUserDto);
        //生成value
        loginPatientUserDto.setToken(token);
        //对象转换成json
        String value = JSON.toJSONString(loginPatientUserDto);
        redisTemplate.opsForValue().set(token,value,patientUserTokenTimeOut, TimeUnit.SECONDS);
    }

    /**
     * 存入token
     */
    @Override
    public void setKey(String key, String value) {
        redisTemplate.opsForValue().set(key,value,patientUserTokenTimeOut, TimeUnit.SECONDS);
    }


    /**
     * 通过token获取登录的用户信息
     */
    @Override
    public LoginPatientUserVo getPatientUserByToken(String token) {
        //先根据Token获取
        String json = redisTemplate.opsForValue().get(token);
        if(json == null || json.equals("")){
            return null;
        }
        LoginPatientUserVo loginPatientUserVo = JSON.parseObject(json, LoginPatientUserVo.class);
        return loginPatientUserVo;
    }

    /**
     * 根据token删除token信息
     */
    @Override
    public void deleteByToken(String token) {
        redisTemplate.delete(token);
    }

    /**
     * 删除所有的token
     */
    @Override
    public void deleteTokens() {
        //获取所有的userToken的key
        Set<String> keys = redisTemplate.keys(KeyCommon.USER_TOKEN_KEY + "*");
        //删除
        redisTemplate.delete(keys);
    }
}
